package br.com.hs.biosys.util.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Criptografy.class
 *
 * @author Ranlive Hrysyk
 * @since 19/07/2012
 */
public class Criptografy {

    private static final long serialVersionUID = 1L;
    private String algorithm;
    private String encoding;

    /**
     * Constructor default.
     *
     * @param algorithm the algorithm
     * @param encoding the encoding
     */
    public Criptografy(String algorithm, String encoding) {
        this.algorithm = algorithm;
        this.encoding = encoding;
    }

    /**
     * Criptografar.
     *
     * @param text the text to encript
     * @return the encripted text
     * @throws if the encoding or message digent invalid.
     */
    public String encrypt(String text) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            byte digestBytes[] = messageDigest.digest(text.getBytes(encoding));

            StringBuilder hexString = new StringBuilder();
            for (byte b : digestBytes) {
                hexString.append(String.format("%02X", 0xFF & b));
            }

            return hexString.toString();
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
            throw new SecurityException(ex);
        }
    }
}
